var fs     = require('fs'),
    ENV    = process.env.NODE_ENV || 'development',
    utils;

utils = {
  loadJson: function(filePath, callback) {
    fs.readFile(filePath, 'UTF-8', function(err, data) {
      var tempData = null, tempErr = null;

      if (err) {
        callback(err, null);
      } else {
        try {
          JSON.parse(data);
        }
        catch(err) {
          tempErr = err;
        }

        if (!tempErr) { tempData = JSON.parse(data); }

        callback(tempErr, tempData);
      }
    });
  },
  walkDir: function(dir, callback) {
    var results = [];

    fs.readdir(dir, function(err, list) {
      var pending;

      if (err) { return callback(err); }
      pending = list.length;
      if (!pending) { return callback(null, results); }

      list.forEach(function(file) {
        file = dir + '/' + file;
        fs.stat(file, function(err, stat) {
          if (stat && stat.isDirectory()) {
            utils.walkDir(file, function(err, res) {
              results = results.concat(res);
              if (!--pending) { callback(null, results); }
            });
          } else {
            results.push(file);
            if (!--pending) { callback(null, results); }
          }
        });
      });

    });
  },
  /*
   * Recursively search the directory for all JSON files, parse them
   * and trigger a callback with the contents
   */
  loadConfig: function(directory, callback) {
    utils.walkDir(directory, function(err, files) {
      var pending = files.length,
          configs = {},
          ENV     = process.env.NODE_ENV || 'development';

      files.forEach(function(filePath) {
        utils.loadJson(filePath, function(err, data) {
          var filename;
          if (err) { throw err; }
          filename = filePath.split('/').pop().replace('.json', '');
          configs[filename] = data;

          if (!--pending) {
            configs.site_url  = (configs[ENV].HTTPS) ? 'https://' : 'http://';
            configs.site_url += configs[ENV].HOST + ':' + configs[ENV].PORT;

            callback(configs);
          }
        });
      });
    });
  },
  restrict: function(req, res, next) {
		if (req.session.user) {
			next();
		} else {
			req.session.error = 'Access denied!';
			res.redirect('/login');
		}
	}
};

module.exports = utils;